import argparse
import json
import os.path
from cold_start_analyzer import util
import sqlite3
from cold_start_analyzer.analyzer_factory import AnalyzerFactory
from cold_start_analyzer.report_generator import ReportGenerator


def entry(file_path, thread_name, output_path="./output"):
    print(f"file_path: {file_path}, thread_name: {thread_name}, output_path: {output_path}")
    if not os.path.exists(output_path):
        os.makedirs(output_path)
    connection = None
    try:
        db_file = util.convert_ftrace_to_sqlite(file_path)
        print(f"db_file: {db_file}")
        connection = sqlite3.connect(db_file)
        cursor = connection.cursor()
        factory = AnalyzerFactory(cursor, os.path.join(util.CURRENT_DIR, "config.ini"), thread_name)
        result = factory.analyze()
        
        # 保存JSON结果
        result_json = os.path.join(output_path, "result.json")
        with open(result_json, "w") as file:
            print(json.dumps(result, indent=4, ensure_ascii=False), file=file)
            
        # 生成HTML报告
        generator = ReportGenerator(result_json, output_path)
        generator.generate()
        
    finally:
        if connection:
            connection.close()

def test():
    # entry('./data/hiprofiler_6.1s.htrace', 'ugc.aweme')
    entry('./data/debug6.1.htrace', 'ugc.aweme')

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Analyze trace')
    parser.add_argument('-f', '--file', help='Path to the trace file')
    parser.add_argument('-o', '--output', help='Path to the output file')
    parser.add_argument('-t', '--thread', help='Thread name of the app')
    args = parser.parse_args()
    if args.file:
        entry(args.file, args.thread, args.output)
    else:
        test()

